# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  
  after_filter  :save_last_request_uri
  
  def save_last_request_uri
    if request.get? and response.redirected_to.nil?
      session[:last_request_uri] = session[:this_request_uri]
      session[:this_request_uri] = request.request_uri
      if session[:this_request_uri] != session[:last_request_uri]
        session[:last_unique_request_uri] = session[:last_request_uri] 
      end
    end
  end
  
  helper_method :last_request_uri
  
  def last_request_uri
    if session[:this_request_uri] == request.request_uri
      if session[:this_request_uri] == session[:last_request_uri]
        session[:last_unique_request_uri]
      else
        session[:last_request_uri]
      end
    else
      session[:this_request_uri]
    end
  end
  
  private
  
  def authorize
    user = User.find_by_id(session[:user_id])
    if user
      session[:user_is_admin]   = user.is_admin
      session[:user_is_doffer]  = user.is_doffer
    else
      session[:original_uri] = request.request_uri
      flash[:notice] = "Please Log in"
      redirect_to(:controller => 'login', :action => "login")
    end
    user
  end
  
  def determine_layout
    layout = 'default'
    
    if session[:is_mobile]
      layout = 'mobile'
    end
    layout
  end
end